package com.tuinui.trade.controller.web;

import com.tuinui.trade.entry.TransactionEntry;
import com.tuinui.trade.manager.DataManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: kaweepapkongkittisan
 * Date: 5/25/13
 * Time: 3:44 PM
 * To change this template use File | Settings | File Templates.
 */

@Controller


public class StockTransactionController {
    final public static Logger _log = LoggerFactory.getLogger(BasicController.class);

    @ModelAttribute("transaction")
    public TransactionEntry populateTransaction(HttpServletRequest request,
                                                HttpServletResponse response,
                                                @RequestParam(required=false, value="id") Long id)throws Exception{
        Object object = null;
        TransactionEntry transactionEntry = null;

        if (id != null){
            transactionEntry = DataManager.getInstance().getTransaction(id);
        }else{
            transactionEntry = new TransactionEntry();
            transactionEntry.setOwner(request.getUserPrincipal().getName());
            transactionEntry.setDate(new Date());

        }
        return transactionEntry;
    }

    @RequestMapping(value="/deletetran", method= RequestMethod.GET)
    public ModelAndView deleteTranDisplay(HttpServletRequest request,
                                          HttpServletResponse response,
                                          @ModelAttribute("transaction")TransactionEntry transactionEntry){
        ModelAndView mv = new ModelAndView("deletetran");
        mv.addObject("transaction", transactionEntry);

        return mv;
    }

    @RequestMapping(value="/deletetran", method= RequestMethod.POST)
    public String deleteTran(HttpServletRequest request,
                                          HttpServletResponse response,
                                          @ModelAttribute("transaction")TransactionEntry transactionEntry){
        DataManager.getInstance().deleteTransaction(transactionEntry);
        return "redirect:transactions";
    }
}
